from rest_framework.views import APIView
from rest_framework.response import Response
from ..serializers import userSerializer
from api.wx import wx_login
from django.core.cache import cache
import hashlib, time
from api.models import Wxuser

#前后台登录验证
class Login(APIView):

    def post(self, request):
        param = request.data
        if not param.get('code'):
             return Response({'status':1, "msg":"缺少参数"})
        else:
            code = param.get('code')
            print("code...", code)
            user_data = wx_login.get_login_info(code)
            # print('用户信息>>',user_data)
            if user_data:
                # 先判断数据库是有有数据
                user, created = Wxuser.objects.get_or_create(openid=user_data['openid'])
                user_str = str(userSerializer(user).data)
                val = user_data['session_key'] + "&" + user_data['openid']
                md5 = hashlib.md5()
                md5.update(str(time.clock()).encode('utf-8'))
                md5.update(user_data['session_key'].encode('utf-8'))
                key = md5.hexdigest()
                cache.set(key, val)
                # has_user = Wxuser.objects.filter(openid=user_data['openid']).first()
                # print("has_user", has_user)
                # if not has_user:
                #     Wxuser.objects.create(openid=user_data['openid'])
                # Wxuser.objects.update()
                return Response({
                    'status': 0,
                    'msg': 'ok',
                    'data': {'token': key,
                             'session_key': key,
                             'openId': key}
                })
            else:
                return Response({'status': 2, 'msg': "无效的code"})

